import { Request, Response } from 'express'
import courseService from '../../service/courseService'
import selectHistoriesService from '../../service/selectHistoriesService'
import teacherService from '../../service/teacherService'

class SelectLessonController {

  // 查询所有历史
  async find(req: Request, res: Request) {
    const { stu } = req.params
    const findRes = await selectHistoriesService.find(stu)
    // 取出课程id，操作时间，操作类型
    const filterRes = findRes.map(item => {
      return {
        cid: item.cid,
        selectAt: item.selectAt,
        operation: item.operation
      }
    })
    // TODO BUG：由于根据cid找不到对应课程(可能被删除)，导致 c 为undefined
    // 根据课程id，查询对应课程，对应教师姓名，然后取出部分数据存入
    const newFilterRes = []
    for (let i = 0; i < filterRes.length; i++) {
      const c = await courseService.findById(filterRes[i].cid)
      if (c) {
        const t = await teacherService.findById(c.teacher_id)
        newFilterRes.push(Object.assign(filterRes[i], {
          cname: c.course_name,
          lesson_period: c.lesson_period,
          type: c.type,
          location: c.location,
          credit: c.credit,
          tname: t.name
        }))
      }
    }
    res.gsmd(filterRes)
  }

  // 清除历史
  async clear(req: Request, res: Request) {
    const { stu } = req.params
    const histories = await selectHistoriesService.find(stu)
    const ids: any = histories.map(item => item.id)
    for (let i = 0; i < ids.length; i++) {
      await selectHistoriesService.deleteById(ids[i])
    }
    res.gsm('清除历史成功！')
  }

}

export default new SelectLessonController()